import random

def load_iris_dataset(filename):
    dataset = []
    with open(filename, 'r') as file:
        for line in file.readlines():
            values = line.strip().split(',')
            if len(values) < 5: 
                continue
            try:
                features = [float(value) for value in values[:-1]]
                label = values[-1]
                if label == 'Iris-setosa':
                    label = 0
                elif label == 'Iris-versicolor':
                    label = 1
                elif label == 'Iris-virginica':
                    label = 2
                dataset.append(features + [label])
            except ValueError:
                print(f"Error processing line: {line}")
    return dataset

def euclidean_distance(row1, row2):
    distance = 0
    for i in range(len(row1) - 1):  # Exclude the last element (label)
        distance += (row1[i] - row2[i]) ** 2
    return distance ** 0.5

def get_neighbors(training_set, test_row, k):
    distances = []
    for train_row in training_set:
        dist = euclidean_distance(test_row, train_row)
        distances.append((train_row, dist))
    distances.sort(key=lambda x: x[1])
    neighbors = []
    for i in range(k):
        neighbors.append(distances[i][0])
    return neighbors

def predict_classification(training_set, test_row, k):
    neighbors = get_neighbors(training_set, test_row, k)
    output_values = [row[-1] for row in neighbors]
    prediction = max(set(output_values), key=output_values.count)
    return prediction

if __name__ == "__main__":

    iris_dataset = load_iris_dataset('iris.data')

    random.seed(7)
    random.shuffle(iris_dataset)
    training_set = iris_dataset[:int(0.8 * len(iris_dataset))]
    test_set = iris_dataset[int(0.8 * len(iris_dataset)):]

    for row in test_set:
        prediction = predict_classification(training_set, row, 5)
        print(f'Actual: {row[-1]}, Predicted: {prediction}')